<template>
  <div>
    <el-form :model="form">
      <el-form-item label="角色名称">
        <el-input v-model="form.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="角色代码">
        <el-input v-model="form.code" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input type="textarea" v-model="form.description"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onCancel">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { saveOrUpdate, getRoleById } from '@/services/role'
export default {
  name: 'CreateOrEdit',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: [Number, String]
    }
  },
  created () {
    if (this.isEdit === true) {
      // 判断如果是编辑功能，则根据id查询角色
      this.loadRole()
    }
  },
  data () {
    return {
      form: {
        name: '',
        code: '',
        description: ''
      }
    }
  },
  methods: {
    async onSubmit () {
      const { data } = await saveOrUpdate(this.form)
      if (data.code === '000000') {
        // 添加成功，触发自定义事件
        this.$emit('success')
        this.$message.success('添加角色成功！')
      }
    },
    onCancel () {
      // 点击取消，触发自定义事件
      this.$emit('cancel')
    },
    async loadRole () {
      const { data } = await getRoleById(this.roleId)
      if (data.code === '000000') {
        this.form = data.data
      }
    }
  }
}

</script>
<style lang='scss' scoped>
</style>
